<template>
  <div class="file-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文件列表</span>
          <el-button type="primary" @click="refreshFiles" :loading="loading">
            刷新列表
          </el-button>
        </div>
      </template>

      <el-table :data="files" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="文件名" min-width="200" />
        <el-table-column prop="size" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="isPublic" label="访问权限" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isPublic ? 'success' : 'warning'">
              {{ row.isPublic ? '公开' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                @click="handlePreview(row)"
                :disabled="!row.isPublic"
              >
                预览
              </el-button>
              <el-button
                type="primary"
                link
                @click="handleDownload(row)"
              >
                下载
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="previewVisible"
      title="文件预览"
      width="80%"
      :before-close="handlePreviewClose"
    >
      <div class="preview-content">
        <img
          v-if="previewFile && isImage(previewFile.type)"
          :src="previewFile.url"
          class="preview-image"
        />
        <iframe
          v-else-if="previewFile && isPdf(previewFile.type)"
          :src="previewFile.url"
          class="preview-pdf"
        />
        <div v-else class="preview-unsupported">
          该文件类型不支持预览
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ossApi } from '../api/oss';
import type { OssFile } from '../types/oss';

const files = ref<OssFile[]>([]);
const loading = ref(false);
const previewVisible = ref(false);
const previewFile = ref<OssFile | null>(null);

const loadFiles = async () => {
  try {
    loading.value = true;
    const response = await ossApi.getFiles();
    files.value = response.data;
  } catch (error) {
    ElMessage.error('获取文件列表失败');
    console.error('获取文件列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const refreshFiles = () => {
  loadFiles();
};

const handlePreview = (file: OssFile) => {
  previewFile.value = file;
  previewVisible.value = true;
};

const handlePreviewClose = () => {
  previewVisible.value = false;
  previewFile.value = null;
};

const handleDownload = (file: OssFile) => {
  window.open(file.url, '_blank');
};

const handleDelete = async (file: OssFile) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件 "${file.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await ossApi.deleteFile(file.path);
    ElMessage.success('文件删除成功');
    refreshFiles();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('文件删除失败');
      console.error('文件删除失败:', error);
    }
  }
};

const formatFileSize = (size: number): string => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  }
};

const isImage = (type: string): boolean => {
  return type.startsWith('image/');
};

const isPdf = (type: string): boolean => {
  return type === 'application/pdf';
};

onMounted(() => {
  loadFiles();
});
</script>

<style scoped>
.file-list {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
}

.preview-pdf {
  width: 100%;
  height: 600px;
  border: none;
}

.preview-unsupported {
  color: #909399;
  font-size: 16px;
}
</style>